import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast, Popup } from 'antd-mobile';
import { getUserInfo } from '../utils/auth';
import axios from 'axios';
import styles from './My.module.css';
import { debounce } from 'lodash';
import  {http,host,port} from '../utils/host'
function My() {
    const navigate = useNavigate();
    const [userInfo, setUserInfo] = useState<any>(null);

    useEffect(() => {
        // 获取用户信息
        const user = getUserInfo();
        setUserInfo(user);
    }, []);

    // 处理功能项点击
    const handleQuickItemClick = (type: string) => {
        switch (type) {
            case 'repair':
                Toast.show({ content: '报修记录功能开发中' });
                break;
            case 'comment':
                Toast.show({ content: '评论/回复功能开发中' });
                break;
            case 'like':
                Toast.show({ content: '点赞/收藏功能开发中' });
                break;
            case 'history':
                Toast.show({ content: '历史浏览功能开发中' });
                break;
            default:
                break;
        }
    };

    // 处理服务项点击
    const handleServiceItemClick = (type: string) => {
        switch (type) {
            case 'campusCard':
                Toast.show({ content: '校园卡功能开发中' });
                break;
            case 'customerService':
                Toast.show({ content: '客服中心功能开发中' });
                break;
            case 'feedback':
                Toast.show({ content: '意见反馈功能开发中' });
                break;
            default:
                break;
        }
    };
    // 刷新用户信息
    const handleRefreshUserInfo = debounce(async () => {
        try {
            const localUserInfo = getUserInfo();
            if (!localUserInfo?.studentId) {
                Toast.show({ content: '请先登录' });
                return;
            }

            // 从数据库获取最新的用户信息
            const response = await axios.get(`${http}${host}${port}/user/${localUserInfo.studentId}`);

            if (response.data.code === 200) {
                const updatedUserInfo = response.data.data;

                // 更新本地存储
                localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));

                // 更新状态
                setUserInfo(updatedUserInfo);

                Toast.show({ content: '用户信息已更新' });
            } else {
                Toast.show({ content: '获取用户信息失败' });
            }
        } catch (error) {
            console.error('刷新用户信息失败:', error);
            Toast.show({ content: '刷新失败，请检查网络连接' });
        }
    }, 1000);
    return (
        <div className={styles.myPage}>
            {/* 顶部用户信息区域 */}
            <div className={styles.userHeader}>
                <div className={styles.headerTop}>
                    <div className={styles.headerIcons}>
                        <div className={styles.iconRefresh} onClick={handleRefreshUserInfo} title="刷新用户信息">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M23 4v6h-6" />
                                <path d="M1 20v-6h6" />
                                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
                            </svg>
                        </div>
                        <div className={styles.iconSettings} onClick={() => navigate('/myprivacy')} title="设置">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <circle cx="12" cy="12" r="3" />
                                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
                            </svg>
                        </div>
                    </div>
                </div>
                <div className={styles.userInfo}>
                    <div className={styles.avatar}>
                        {(() => {
                            // 优先使用本地存储的 userAvatar
                            const localUserAvatar = localStorage.getItem('userAvatar');
                            if (localUserAvatar) {
                                return <img src={localUserAvatar} alt="用户头像" onError={(e) => {
                                    // 如果本地存储的头像加载失败，回退到默认头像
                                    (e.target as HTMLImageElement).src = "";
                                }} />;
                            }
                            // 其次使用用户信息中的 avatarImage
                            else if (userInfo?.avatarImage) {
                                return <img src={userInfo.avatarImage} alt="用户头像" onError={(e) => {
                                    // 如果用户信息中的头像加载失败，回退到默认头像
                                    (e.target as HTMLImageElement).src = "";
                                }} />;
                            }
                            // 最后使用默认头像
                            else {
                                return <img src="" alt="默认头像" />;
                            }
                        })()}
                    </div>
                    <div className={styles.userDetails}>
                        <div className={styles.username}>
                                {userInfo?.username ?
                                    <span>{userInfo?.username}</span> : <span onClick={() => navigate('/login')}>未登录</span>}
                                <span className={styles.editIcon} onClick={()=>navigate('/renlian')}>&nbsp;&nbsp;✏</span>
                        </div>
                        <div className={styles.userMeta}>
                            <span className={styles.schoolName}>{userInfo?.schoolName || '请先登录'}</span>
                            <span className={styles.studentId}>{userInfo?.studentId || ''}</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* 统计数据卡片 */}
            <div className={styles.statsCard}>
                <div className={styles.statItem}>
                    <div className={styles.statNumber}>102</div>
                    <div className={styles.statLabel}>获赞</div>
                </div>
                <div className={styles.statItem}>
                    <div className={styles.statNumber}>4</div>
                    <div className={styles.statLabel}>粉丝</div>
                </div>
                <div className={styles.statItem}>
                    <div className={styles.statNumber}>0</div>
                    <div className={styles.statLabel}>关注</div>
                </div>
                <div className={styles.statItem}>
                    <div className={styles.statNumber}>100</div>
                    <div className={styles.statLabel}>访客</div>
                </div>
            </div>

            {/* 快捷功能卡片 */}
            <div className={styles.quickAccessCard}>
                <div className={styles.quickItem} onClick={() => handleQuickItemClick('repair')}>
                    <div className={styles.quickIcon}>🔧</div>
                    <div className={styles.quickLabel}>报修记录</div>
                </div>
                <div className={styles.quickItem} onClick={() => handleQuickItemClick('comment')}>
                    <div className={styles.quickIcon}>💬</div>
                    <div className={styles.quickLabel}>评论/回复</div>
                </div>
                <div className={styles.quickItem} onClick={() => handleQuickItemClick('like')}>
                    <div className={styles.quickIcon}>⭐</div>
                    <div className={styles.quickLabel}>点赞/收藏</div>
                </div>
                <div className={styles.quickItem} onClick={() => handleQuickItemClick('history')}>
                    <div className={styles.quickIcon}>⏰</div>
                    <div className={styles.quickLabel}>历史浏览</div>
                </div>
            </div>

            {/* 服务中心卡片 */}
            <div className={styles.serviceCenterCard}>
                <div className={styles.serviceTitle}>服务中心</div>
                <div className={styles.serviceItem} onClick={() => handleServiceItemClick('campusCard')}>
                    <div className={styles.serviceIcon}>🎫</div>
                    <div className={styles.serviceLabel}>校园卡</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
                <div className={styles.serviceItem} onClick={() => handleServiceItemClick('customerService')}>
                    <div className={styles.serviceIcon}>🎧</div>
                    <div className={styles.serviceLabel}>客服中心</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
                <div className={styles.serviceItem} onClick={() => handleServiceItemClick('feedback')}>
                    <div className={styles.serviceIcon}>📝</div>
                    <div className={styles.serviceLabel}>意见反馈</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
            </div>

            {/* 其他功能卡片 */}
            <div className={styles.otherFunctionsCard}>
                <div className={styles.serviceTitle}>其他功能</div>
                <div className={styles.serviceItem} onClick={() => navigate('/renlian')}>
                    <div className={styles.serviceIcon}>🔒</div>
                    <div className={styles.serviceLabel}>隐私设置</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
                <div className={styles.serviceItem}>
                    <div className={styles.serviceIcon}>📱</div>
                    <div className={styles.serviceLabel}>关于我们</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
                <div className={styles.serviceItem}>
                    <div className={styles.serviceIcon}>📖</div>
                    <div className={styles.serviceLabel}>使用帮助</div>
                    <div className={styles.serviceArrow}>{'>'}</div>
                </div>
            </div>


        </div>
    );
}

export default My; 
